package com.ruoyi.wetest.stats;

import com.codahale.metrics.Reservoir;
import com.codahale.metrics.Snapshot;
import org.apache.lucene.util.RamUsageEstimator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author Allen
 * @description 压测专家压缩版统计水池
 * @Date 2024/5/16 17:51
 */
public class WeTestUniform2Reservoir implements Reservoir {

    private final AtomicLong count = new AtomicLong();
    private final HashMap<Long, Integer> values;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());



    public WeTestUniform2Reservoir(int size) {
        this.values = new HashMap<>();
    }

    @Override
    public int size() {
        final long c = count.get();
        synchronized (this) {
            if (c > values.size()) {
                return values.size();
            }
        }
        return (int) c;
    }

    @Override
    public void update(long value) {
        count.incrementAndGet();
        synchronized (this) {
            Integer i = values.get(value);
            if (i == null) {
                i = 1;
            } else {
                i++;
            }
            values.put(value, i);
        }

    }

    /**
     * 内存占用内存大小
     * @return
     */
    public long getMemSize() {
        return RamUsageEstimator.sizeOf(values);
    }

    @Override
    public Snapshot getSnapshot() {
        synchronized (this) {
            Map<Long, Integer> copy = new HashMap<>(values);
            return new WeTestUniformSnapshot(copy);
        }
    }
}
